// pages/teamChat/index.js
import {userStore} from "../../store/index"
const app = getApp()
Page({
  data: {
    userInfo:{},
    msg:[],
    msgText:"",
    setPosition:0,
    msgHeight:200
  },
  onLoad: function (options) {
    wx.showLoading({
      title: '连接中',
    })
    userStore.dispatch("_wsSend")
    this.setupUserInfoStore()
  },
  onReady:function(){
    this.inputBlurHandle()
  },
  onShow: function () {
    userStore.dispatch("_getMsg")
  },
  onUnload:function(){
    userStore.dispatch("closeSocket")
  },
  async sendHandle(){
    if(this.data.msgText !== ""){
      const time = new Date().getTime()
      let msgItem = {
        time:time,
        text:this.data.msgText,
        nickName:this.data.userInfo.nickName,
        imgUrl:this.data.userInfo.avatarUrl
      }
      this.setData({msgText:""})
      // userStore.dispatch("_addMsg",{msgItem})
      let jsMsg = JSON.stringify(msgItem)
      await userStore.dispatch("sendSocketMessage",{msg:jsMsg})
    }
    userStore.dispatch("pageScrollToBottom")
  },
  inputHandle(e){
    this.setData({msgText:e.detail.value})
  },
  inputFocusHandle(e){
    let height = e.detail.height
    let inputHeight = app.globalData.windowHeight - height - 39 - 15
    this.setData({msgHeight:inputHeight})
    userStore.dispatch("pageScrollToBottom")
  },
  inputBlurHandle(e){
    let inputHeight = app.globalData.windowHeight - 39-15
    this.setData({msgHeight:inputHeight})
    this.setData({msgText:""})
  },
  setupUserInfoStore(){
    userStore.onStates(["userInfo"],({userInfo})=>{
      if(userInfo) this.setData({userInfo})
    })
    userStore.onStates(["msg"],({msg})=>{
      if(msg) this.setData({msg})
    })
    userStore.onStates(["setPosition"],({setPosition})=>{
      this.setData({setPosition})
    })
  }
})